package com.clouddot.baipai.ui.receiver;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.beam.getClassType.getClassTypeResponse;
import com.clouddot.baipai.ui.activity.A_LaunchActivity;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.ui.util.netConnectUtil.isNetworkConnected;

public class MyReceiver extends BroadcastReceiver {

    public MyReceiver() {

    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        Log.e("接收开机广播", "有广播进入");
        if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")
                 || intent.getAction().equals("android.intent.action.MEDIA_MOUNTED")
                 || intent.getAction().equals("android.intent.action.MEDIA_UNMOUNTED")
                 || intent.getAction().equals("android.intent.action.MEDIA_EJECT")) {
                   ThreadPoolFactory.getThread().execute(new Runnable() {
                        @Override
                        public void run() {

                        while(true) {
                            if (isNetworkConnected(context)) {
                                Message msg = new Message();
                                msg.obj = context;
                                msg.what = MSG_ONE;
                                handler.sendMessage(msg);

                                getClassTypeResponse response = Env.getAppPresenter().getClassType();
                                if (response.isSuccess()) {
                                    String[] startTime = response.ChooseStartMechine.contains(":") ? response.ChooseStartMechine.split(":") : "7:00".split(":");
                                    String[] endTime = response.ChooseShutdownMechine.contains(":") ? response.ChooseShutdownMechine.split(":") : "19:00".split(":");
                                    if(Environment.getInstance().Height <= 100) {
                                        if (response.CardReadType.equals("Serial")) {
                                            Calendar c = Calendar.getInstance();
                                            int mYear = c.get(Calendar.YEAR);
                                            int mMonth = c.get(Calendar.MONTH) + 1;
                                            int mDay = c.get(Calendar.DAY_OF_MONTH);
                                            Intent intent = new Intent("android.intent.action.setpoweronoff");
                                            int[] timeon = new int[]{mYear, mMonth, mDay, Integer.parseInt(startTime[0]), Integer.parseInt(startTime[1]), 0}; //开机时间
                                            intent.putExtra("timeon", timeon);
                                            int[] timeoff = new int[]{mYear, mMonth, mDay, Integer.parseInt(endTime[0]), Integer.parseInt(endTime[1]), 0}; //关机时间
                                            intent.putExtra("timeoff", timeoff);
                                            intent.putExtra("enable", true);
                                            context.sendBroadcast(intent);
                                        }
                                    }else{
                                        Intent clearIntent = new Intent("android.intent.action.DELETE_ALARM_BY_SERVER");
                                        clearIntent.putExtra("delete_all", true);
                                        context.sendOrderedBroadcast(clearIntent, null);

                                        Intent end = new Intent("android.intent.action.ADD_ALARM_BY_SERVER");
                                        end.putExtra("hour", Integer.parseInt(endTime[0]));
                                        end.putExtra("minute", Integer.parseInt(endTime[1]));
                                        end.putExtra("mAttribute", 2);
                                        end.putExtra("daysOfWeek", 0x7f);
                                        context.sendOrderedBroadcast(end, null);

                                        Intent start = new Intent("android.intent.action.ADD_ALARM_BY_SERVER");
                                        start.putExtra("hour",  Integer.parseInt(startTime[0]));
                                        start.putExtra("minute",  Integer.parseInt(startTime[1]));
                                        start.putExtra("mAttribute", 1);
                                        start.putExtra("daysOfWeek", 0x7f);
                                        context.sendOrderedBroadcast(start, null);
                                    }
                                }else{
                                    ToastUtil.showToast(context,"更新定时开关机失败");
                                }
                                break;
                            }
                        }
                    }
                });
        } else if (
                intent.getAction().equals("android.NET.conn.CONNECTIVITY_CHANGE") ||
                intent.getAction().equals("android.Net.wifi.WIFI_STATE_CHANGED") ||
                intent.getAction().equals("android.net.wifi.STATE_CHANGE")) {
                Intent i = new Intent();
                i.setAction("net.state.change");
                context.sendBroadcast(i);
        }else if( intent.getAction().equals("com.android.settings.action.REQUEST_POWER_OFF")){
            try {
                Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                proc.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    /**
     *
     * 结束获取信息的handle机制
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    Context context = (Context) msg.obj;
                    Intent i = new Intent(context, A_LaunchActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                    break;
                default:
                    break;
            }
        }
    };

}
